package com.lvyq.myplayer.dao

import androidx.room.*
import com.lvyq.myplayer.model.cache.PlayCacheEntity
import com.lvyq.myplayer.model.collect.PlayCollectEntity
import com.lvyq.myplayer.model.history.PlayHistoryEntity
import kotlinx.coroutines.flow.Flow

/**
 * 文件描述：PlayCollectDao
 * 作者：lvyq
 * 创建时间：2025-06-16
 * 修改时间：2025-06-16
 */

@Dao
interface PlayCacheDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertPlayCache(data: PlayCacheEntity)

    @Update
    suspend fun updatePlayCache(data: PlayCacheEntity)

    @Delete
    suspend fun deletePlayCache(data: PlayCacheEntity)

    //使用 Flow返回列表 当数据库中的播放历史数据发生变化时，Flow 会自动发射（emit）最新的数据 根据时间倒序
    //在 collect 块中监听数据流，一旦有新数据（如删除操作后），会立即触发 UI 更新
    //支持多次发射
    //LiveData仅支持单次数据发射，需手动刷新（如调用 observe 重新订阅）
    @Query("SELECT * FROM play_cache_song WHERE type =:type ORDER BY updateTime DESC")
     fun getAllPlayCacheListFlow(type: Int): Flow<List<PlayCacheEntity> >

    @Query("SELECT * FROM play_cache_song WHERE id = :id")
     fun getPlayCacheById(id: Int): PlayCacheEntity?

    /**
     * 根据businessKey和type查询
     */
    @Query("SELECT * FROM play_cache_song WHERE businessKey = :businessKey AND type= :type")
    suspend   fun getPlayCacheByBusinessKeyAndType(businessKey:Int,type:Int):PlayCacheEntity?

    @Query("SELECT * FROM play_cache_song WHERE title LIKE '%' || :query || '%'")
    fun searchPlayCacheList(query: String): List<PlayCacheEntity>

    @Query("SELECT count(id) FROM play_cache_song WHERE type =:type")
    fun count(type: Int):Flow<Long>
    @Query("SELECT count(id) FROM play_cache_song ")
    fun count():Flow<Long>
    @Query("DELETE FROM play_cache_song WHERE id IN (:ids)")
    suspend fun deleteByIds(ids: List<Int>)
    @Query("DELETE FROM play_cache_song WHERE businessKey = :businessKey and type= :type")
    suspend fun deleteByBusinessKey(businessKey: Int,type:Int)
}
